<?php
namespace Helper;
class MagicCrypt
{
    protected $td = '';
    protected $iv = '';
    protected $key = '';
    private static $instance = null;

    private function __construct($cipher,$mode,$key,$iv)
    {
        $this->cipher = $cipher;
        $this->mode = $mode;
        $this->key = $key;
        $this->iv = $iv;
    }

    public static function getInstance($cipher=MCRYPT_RIJNDAEL_128,$mode=MCRYPT_MODE_CBC,$key='kf-system',$iv="1234567899876543")
    {
        if(self::$instance === null){
            self::$instance = new self($cipher,$mode,$key ,$iv);
        }
        return self::$instance;
    }

    public function encrypt($str)
    {
        $td = mcrypt_module_open($this->cipher,'',$this->mode,'');//打开算法模块


        $num = mcrypt_generic_init($td,$this->key, $this->iv);//初始化加密空间
        $encrypt = mcrypt_generic($td,$str);//执行加密
        mcrypt_generic_deinit($td);//结束加密，执行清理工作
        return base64_encode($encrypt);
    }

    public function decrypt($str)
    {
        $str = base64_decode($str,true);
        if(!$str){
            return false;
        }

        $td = mcrypt_module_open($this->cipher,'',$this->mode,'');//打开算法模块
        mcrypt_generic_init($td,$this->key,$this->iv);
        $decrypt = rtrim(mdecrypt_generic($td,$str));
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);//关闭算法模块
        return $decrypt;
    }
}

?>